package com.ihr360.commons.lang;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

public class PageUtil {

    public static Pageable getPageable(Integer page, Integer rows, Sort sort) {
        if (rows != null && rows > 100) {
            throw new RuntimeException("最大只能查询100条！");
        }
        int intPage = page == null || page <= 0 ? 1 : page;
        int intPageSize = rows == null || rows <= 0 || rows > 100 ? 100 : rows;
        return new PageRequest(intPage - 1, intPageSize, sort);
    }

    public static Pageable getPageable(Integer page, Integer rows) {
        if (rows != null && rows > 100) {
            throw new RuntimeException("最大只能查询100条！");
        }
        int intPage = page == null || page <= 0 ? 1 : page;
        int intPageSize = rows == null || rows <= 0 || rows > 100 ? 100 : rows;
        return new PageRequest(intPage - 1, intPageSize);
    }

    public static Pageable getPageable(Integer page, Integer rows, String sortId, Boolean sortAsc, String defaultSortId) {
        Sort sort;
        if (!StringUtils.isEmpty(sortId) && sortAsc != null) {
            if (sortAsc) {
                sort = new Sort(Sort.Direction.ASC, sortId);
            } else {
                sort = new Sort(Sort.Direction.DESC, sortId);
            }
        } else {
            sort = new Sort(Sort.Direction.DESC, defaultSortId);
        }
        return getPageable(page, rows, sort);
    }

}
